from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login
from django.http import HttpResponseForbidden, JsonResponse
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.core.management import call_command
from django.core.paginator import Paginator
from io import StringIO
from functools import wraps
import sys
from datetime import datetime
from .forms import CustomUserCreationForm, UserUpdateForm, RoleForm, MenuForm, UserUpdateWithPasswordForm, AdminUserUpdateForm
from .models import Role, Menu, Permission

User = get_user_model()

# 自定义权限检查装饰器
def account_permission_required(permission_name):
    def decorator(view_func):
        def _wrapped_view(request, *args, **kwargs):
            # 超级用户拥有所有权限
            if request.user.is_superuser:
                return view_func(request, *args, **kwargs)
            
            # 检查用户是否有对应权限
            user_permissions = request.user.get_user_permissions()
            if permission_name in user_permissions:
                return view_func(request, *args, **kwargs)
            else:
                messages.error(request, '您没有执行此操作的权限')
                return redirect('accounts:user_list')
        return _wrapped_view
    return decorator

# Create your views here.

def register(request):
    """
    用户注册视图
    """
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            messages.success(request, '注册成功，请登录')
            return redirect('accounts:login')
    else:
        form = CustomUserCreationForm()
    
    return render(request, 'accounts/register.html', {'form': form})


def user_login(request):
    """
    用户登录视图
    """
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        
        user = authenticate(request, username=username, password=password)
        
        if user is not None:
            login(request, user)
            # 登录成功后重定向到欢迎页面或用户之前访问的页面
            next_page = request.GET.get('next', 'accounts:welcome')
            return redirect(next_page)
        else:
            messages.error(request, '用户名或密码错误')
    
    return render(request, 'accounts/login.html')


def user_login_without_nav(request):
    """
    无导航栏的用户登录视图（用于退出登录后跳转）
    """
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        
        user = authenticate(request, username=username, password=password)
        
        if user is not None:
            login(request, user)
            # 登录成功后重定向到欢迎页面或用户之前访问的页面
            next_page = request.GET.get('next', 'accounts:welcome')
            return redirect(next_page)
        else:
            messages.error(request, '用户名或密码错误')
    
    # 对于GET请求，也需要检查用户是否已经登录
    if request.user.is_authenticated:
        # 如果用户已经登录，重定向到欢迎页面
        return redirect('accounts:welcome')
    
    return render(request, 'accounts/login_without_nav.html')


@login_required
def user_logout(request):
    """
    用户退出登录视图
    """
    # 使用Django内置的logout函数来正确清理会话
    from django.contrib.auth import logout
    logout(request)
    
    # 重定向到无导航栏的登录页面
    return redirect('accounts:login_without_nav')


def index(request):
    """
    根路径视图，根据用户登录状态重定向到相应页面
    """
    if request.user.is_authenticated:
        return redirect('accounts:dashboard')
    else:
        return redirect('accounts:login')


@login_required
def dashboard(request):
    """
    系统仪表板页面
    """
    # 获取系统统计数据
    user_count = User.objects.count()
    role_count = Role.objects.count()
    permission_count = Permission.objects.count()
    menu_count = Menu.objects.count()
    
    # 获取最近的用户
    recent_users = User.objects.order_by('-date_joined')[:5]
    
    # 获取当前用户的角色
    user_roles = request.user.roles.all()
    
    # 获取当前用户的权限数量
    user_permissions_count = 0
    for role in user_roles:
        user_permissions_count += role.permissions.count()
    
    context = {
        'user_count': user_count,
        'role_count': role_count,
        'permission_count': permission_count,
        'menu_count': menu_count,
        'recent_users': recent_users,
        'user_roles': user_roles,
        'user_permissions_count': user_permissions_count,
    }
    
    return render(request, 'accounts/dashboard.html', context)


@login_required
def welcome(request):
    """
    欢迎页面视图
    """
    # 获取当前用户的角色
    user_roles = request.user.roles.all()
    
    # 获取当前用户的权限数量
    user_permissions_count = 0
    for role in user_roles:
        user_permissions_count += role.permissions.count()
    
    context = {
        'current_time': datetime.now(),
        'user_permissions_count': user_permissions_count,
        'user_roles': user_roles,
    }
    
    return render(request, 'accounts/welcome.html', context)


@login_required
def sync_permissions(request):
    """
    同步权限视图
    """
    if not request.user.is_superuser:
        return HttpResponseForbidden("您没有权限执行此操作")
    
    if request.method == 'POST':
        try:
            # 调用管理命令同步权限
            output = StringIO()
            call_command('sync_permissions', stdout=output)
            result = output.getvalue()
            # 移除ANSI转义序列（颜色代码）
            import re
            clean_result = re.sub(r'\x1b\[[0-9;]*m', '', result)
            messages.success(request, f'权限同步完成: {clean_result}')
        except Exception as e:
            messages.error(request, f'权限同步失败: {str(e)}')
        
        return redirect('accounts:role_list')
    
    return render(request, 'accounts/sync_permissions.html')


# 用户管理视图
@login_required
@account_permission_required('accounts:user_list')
def user_list(request):
    """
    用户列表页面
    """
    users = User.objects.all().order_by('-date_joined')  # 按创建时间倒序排列
    
    # 添加分页功能
    paginator = Paginator(users, 10)  # 每页显示10个用户
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # 获取用户权限
    user_permissions = request.user.get_user_permissions()
    
    context = {
        'page_obj': page_obj,
        'user_permissions': user_permissions
    }
    
    return render(request, 'accounts/user_list.html', context)


@login_required
@account_permission_required('accounts:user_create')
def user_create(request):
    """
    创建用户
    """
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            # 处理角色分配
            roles = form.cleaned_data.get('roles')
            if roles:
                user.roles.set(roles)
            messages.success(request, '用户创建成功')
            return redirect('accounts:user_list')
    else:
        form = CustomUserCreationForm()
    
    return render(request, 'accounts/user_form.html', {'form': form, 'title': '创建用户'})


@login_required
@account_permission_required('accounts:user_update')
def user_update(request, pk):
    """
    更新用户
    """
    user = get_object_or_404(User, pk=pk)
    
    if request.method == 'POST':
        form = AdminUserUpdateForm(request.POST, instance=user)
        if form.is_valid():
            form.save()
            messages.success(request, '用户信息更新成功')
            return redirect('accounts:user_list')
    else:
        form = AdminUserUpdateForm(instance=user)
    
    return render(request, 'accounts/user_form.html', {'form': form, 'title': '编辑用户', 'user_obj': user, 'show_password_fields': True})


@login_required
@account_permission_required('accounts:user_delete')
def user_delete(request, pk):
    """
    删除用户
    """
    user = get_object_or_404(User, pk=pk)
    
    if request.method == 'POST':
        user.delete()
        messages.success(request, '用户删除成功')
        return redirect('accounts:user_list')
    
    return render(request, 'accounts/user_confirm_delete.html', {'user': user})


# 角色管理视图
@login_required
@account_permission_required('accounts:role_list')
def role_list(request):
    """
    角色列表页面
    """
    roles = Role.objects.all().order_by('name')  # 按角色名称排序
    
    # 添加分页功能
    paginator = Paginator(roles, 10)  # 每页显示10个角色
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # 获取用户权限
    user_permissions = request.user.get_user_permissions()
    
    context = {
        'page_obj': page_obj,
        'user_permissions': user_permissions
    }
    
    # 检查是否是Ajax请求
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        # 对于Ajax请求，只返回内容部分
        return render(request, 'accounts/role_list.html', context)
    
    return render(request, 'accounts/role_list.html', context)


@login_required
@account_permission_required('accounts:role_create')
def role_create(request):
    """
    创建角色
    """
    if request.method == 'POST':
        form = RoleForm(request.POST)
        if form.is_valid():
            role = form.save()
            messages.success(request, '角色创建成功')
            return redirect('accounts:role_list')
    else:
        form = RoleForm()
    
    return render(request, 'accounts/role_form.html', {'form': form, 'title': '创建角色'})


@login_required
@account_permission_required('accounts:role_update')
def role_update(request, pk):
    """
    更新角色
    """
    role = get_object_or_404(Role, pk=pk)
    
    if request.method == 'POST':
        form = RoleForm(request.POST, instance=role)
        if form.is_valid():
            form.save()
            messages.success(request, '角色信息更新成功')
            return redirect('accounts:role_list')
    else:
        form = RoleForm(instance=role)
    
    return render(request, 'accounts/role_form.html', {'form': form, 'title': '编辑角色', 'role': role})


@login_required
@account_permission_required('accounts:role_delete')
def role_delete(request, pk):
    """
    删除角色
    """
    role = get_object_or_404(Role, pk=pk)
    
    if request.method == 'POST':
        role.delete()
        messages.success(request, '角色删除成功')
        return redirect('accounts:role_list')
    
    return render(request, 'accounts/role_confirm_delete.html', {'role': role})


# 菜单管理视图
@login_required
@account_permission_required('accounts:menu_list')
def menu_list(request):
    """
    菜单列表页面
    """
    menus = Menu.objects.filter(parent=None).order_by('order')
    
    # 添加分页功能
    paginator = Paginator(menus, 10)  # 每页显示10个菜单
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # 获取用户权限
    user_permissions = request.user.get_user_permissions()
    
    context = {
        'page_obj': page_obj,
        'user_permissions': user_permissions
    }
    
    # 检查是否是Ajax请求
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        # 对于Ajax请求，只返回内容部分
        return render(request, 'accounts/menu_list.html', context)
    
    return render(request, 'accounts/menu_list.html', context)


@login_required
@account_permission_required('accounts:menu_create')
def menu_create(request):
    """
    创建菜单
    """
    if request.method == 'POST':
        form = MenuForm(request.POST)
        if form.is_valid():
            menu = form.save()
            messages.success(request, '菜单创建成功')
            return redirect('accounts:menu_list')
    else:
        form = MenuForm()
    
    return render(request, 'accounts/menu_form.html', {'form': form, 'title': '创建菜单'})


@login_required
@account_permission_required('accounts:menu_update')
def menu_update(request, pk):
    """
    更新菜单
    """
    menu = get_object_or_404(Menu, pk=pk)
    
    if request.method == 'POST':
        form = MenuForm(request.POST, instance=menu)
        if form.is_valid():
            form.save()
            messages.success(request, '菜单信息更新成功')
            return redirect('accounts:menu_list')
    else:
        form = MenuForm(instance=menu)
    
    return render(request, 'accounts/menu_form.html', {'form': form, 'title': '编辑菜单', 'menu': menu})


@login_required
@account_permission_required('accounts:menu_delete')
def menu_delete(request, pk):
    """
    删除菜单
    """
    menu = get_object_or_404(Menu, pk=pk)
    
    if request.method == 'POST':
        menu.delete()
        messages.success(request, '菜单删除成功')
        return redirect('accounts:menu_list')
    
    return render(request, 'accounts/menu_confirm_delete.html', {'menu': menu})


@login_required
def profile(request):
    """
    用户个人信息页面，可以修改个人信息和密码
    """
    if request.method == 'POST':
        form = UserUpdateWithPasswordForm(request.POST, instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, '个人信息更新成功')
            return redirect('accounts:profile')
    else:
        form = UserUpdateWithPasswordForm(instance=request.user)
    
    return render(request, 'accounts/user_form.html', {
        'form': form, 
        'title': '个人信息', 
        'show_password_fields': True,
        'is_profile_page': True
    })


def permission_denied(request):
    """
    权限拒绝页面
    """
    return HttpResponseForbidden("您没有权限访问此页面")